﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentScheduler;
using Simple.Core.Web;

namespace Simple.Job
{
    /// <summary>
    /// 注册任务
    /// </summary>
    public class JobRegistry : Registry
    {
        /// <summary>
        /// 自动注册实现IJob的接口的任务
        /// </summary>
        public JobRegistry()
        {
            Type baseType = typeof(IJobSchedule);
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            var jobTypes = new List<Type>();
            foreach (var assembly in assemblies)
            {
                var types = assembly.GetTypes().Where(t =>
                    t.IsClass && t.GetInterfaces().Any(m => baseType.IsAssignableFrom(m))).ToList();
                jobTypes.AddRange(types);
            }

            foreach (var jobSchedule in jobTypes)
            {
                var job = (IJobSchedule)HostServiceExtension.CreateInstance(jobSchedule);
                var schedule = Schedule(job).WithName(job.JobName)
                    .NonReentrant();//禁止并行执行

                job.ScheduleConfig(schedule);
            }
        }
    }
}
